package com.j4dream.property.service;

import com.google.common.base.Splitter;
import com.j4dream.property.web.exception.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Slf4j
@Service
public class FileService {

    private final long MAX_CSV_SIZE = 100 * 1024 * 1024;

    private Path rootPath;

    private List<String> supportFileTypes;

    public FileService(@Value("${storage.data-file-type}") String fileTypes, @Value("${storage.data-file-root}") String rootPath) {
        this.supportFileTypes = Splitter.on(',')
                .trimResults()
                .splitToList(fileTypes);
        this.rootPath = Paths.get(rootPath);
    }

    public Resource saveDataFile(MultipartFile file, String owner) {
        if (file == null) throw new StorageException("File cannot null");
        if (file.isEmpty()) throw new StorageException("File is empty");
        long size;
        if ((size = file.getSize()) > MAX_CSV_SIZE)
            throw new MaxSizeException(String.format("Your file size is %d, expire max size %d.", size, MAX_CSV_SIZE));

        String originalFilename = file.getOriginalFilename();
        String fileType = com.google.common.io.Files.getFileExtension(originalFilename);
        if (!supportFileTypes.stream().anyMatch(s -> s.equals(fileType))) {
            throw new StorageException(String.format("Unsupport type %s, only support %s.", fileType, supportFileTypes));
        }

        try {
//            InputStream is = file.getInputStream();
//            OutputStream os = new FileOutputStream(new File("data.temp"));
//            int flag = -1;
//            byte[] buffer = new byte[1024];
//            while ((flag = is.read(buffer)) != -1) {
//                os.write(buffer, 0, flag);
//            }
//            is.close();
//            os.close();
            Path path = Paths.get(rootPath.toString(), owner);
            Files.createDirectories(path);
            Path fullPath = path.resolve(originalFilename);
            Files.deleteIfExists(fullPath);
            Files.copy(file.getInputStream(), fullPath);
            log.info(String.format("Save file [%s] in storage path: %s", originalFilename, fullPath.toString()));
            return new UrlResource(fullPath.toUri());
        } catch (IOException e) {
            throw new StorageException(String.format("Fail to save file %s", originalFilename));
        }
    }
}